package com.ruoyi.mdkt.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.mdkt.entity.Student;
import com.ruoyi.mdkt.entity.Teacher;
import com.ruoyi.mdkt.entity.vo.UserVo;
import com.ruoyi.mdkt.service.StudentService;
import com.ruoyi.mdkt.service.TeacherService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@CrossOrigin

@RestController
@RequestMapping("/mdkt/user")
public class UserCotroller {
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private StudentService studentService;

    @GetMapping("/getUser")
    public R<UserVo> getUser(){
        UserVo userVo = new UserVo();
        Long userId = SecurityUtils.getUserId();
        SysUser user = userService.selectUserById(userId);
        userVo.setUserId(userId);
        userVo.setUrl(user.getAvatar());
        userVo.setNickName(user.getNickName());
        List<SysRole> sysRoles = roleService.selectRolesByUserId(userId);
        if ("teacher".equals(sysRoles.get(0).getRoleKey())){
            LambdaQueryWrapper<Teacher> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Teacher::getUserId,userId);
            Teacher one = teacherService.getOne(wrapper);
            userVo.setSign(one.getSign());
        }else{
            LambdaQueryWrapper<Student> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Student::getUserId,userId);
            Student one = studentService.getOne(wrapper);
            userVo.setSign(one.getSign());
        }
        return R.ok(userVo);
    }

    @GetMapping("/searchUser/{name}")
    public R<List<UserVo>> searchUser(@PathVariable String name){
        List<SysUser> users = userService.likeByNickName(name);
        List<UserVo> userVos = users.stream().map((item) -> {
            UserVo userVo = new UserVo();
            userVo.setUserId(item.getUserId());
            userVo.setUrl(item.getAvatar());
            userVo.setNickName(item.getNickName());
            return userVo;
        }).collect(Collectors.toList());
        return R.ok(userVos);
    }

}
